package main

import (
	"fmt"
	"gitee.com/hlwqds/rabitmqTest/log"
	"github.com/streadway/amqp"
	syslog "log"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"
)

func bodyFrom(args []string) int{
	var s string
	if len(args) < 2 || os.Args[1] == "" {
		s = "30"
	}else{
		s = strings.Join(args[1:], " ")
	}
	n, err := strconv.Atoi(s)
	log.FailOnError(err, "Failed to convert arg to integer")

	return n
}

func fibonacciRPC(n int) (res int, err error){
	conn, err := amqp.Dial("amqp://guest:guest@119.45.147.122:5672/")
	log.FailOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	//创建channel
	ch, err := conn.Channel()
	log.FailOnError(err, "Failed to open a channel")
	defer ch.Close()

	err = ch.ExchangeDeclare(
		"confirmPublisher1",
		"direct",
		false,
		false,
		false,
		false,
		nil)
	log.FailOnError(err, "Failed to declare exchange")
	ack := make(chan uint64)
	nAck := make(chan uint64)
	err = ch.Confirm(false)
	log.FailOnError(err, "Failed to set channel confirm")

	for i := 0; i < 4; i++ {
		err = ch.Publish(
			"confirmPublisher1",
			"",
			false,
			false,
			amqp.Publishing{
				ContentType: "text/plain",
				Body: []byte(strconv.Itoa(n)),
			})
		log.FailOnError(err, "Failed to publish a message")
	}

	ch.NotifyConfirm(ack, nAck)
	for ack := range ack {
		fmt.Println(ack)
	}

	return
}

func main(){
	rand.Seed(time.Now().UTC().UnixNano())

	n := bodyFrom(os.Args)

	syslog.Printf(" [x] Requesting fib(%d)", n)
	res, err := fibonacciRPC(n)
	log.FailOnError(err, "Failed to handle RPC request")
	syslog.Printf(" [.] Got %d", res)
}



